<template>
    <div class="background">
        <div class="border">
            <!-- logo -->
            <img class="logo" :src="userData.lightMode ? lightimg : darkimg" alt="" />

            <!-- 标题 -->
            <p class="name">食链智控</p>

            <!-- 输入框 -->
            <el-input class="uinput" :disabled="userInputData.user_enoccupation != 4" v-model="userInputData.username"
                :placeholder="message.username" :prefix-icon="User" />

            <el-input class="uinput" v-model="userInputData.password" :placeholder="message.password" type="password"
                show-password :prefix-icon="Lock" />

            <el-select class="uinput" @change="chaneCharacter(userInputData.user_enoccupation)"
                v-model="userInputData.user_enoccupation" :placeholder="message.user_enoccupation" size="large">
                <el-option v-for="item in user_occupation" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>

            <!-- 验证码 -->
            <div class="codebg">
                <el-input v-model="userInputData.code" :placeholder="message.code" :prefix-icon="CircleCheck" />

                <img :src="captchaImg" @click="getCaptcha" />
            </div>


            <!-- 登录 -->
            <el-button class="loginbtn" type="primary" @click="login">登录</el-button>
            <!-- 注册账号/忘记密码 -->
            <div class="plusFun" v-if="userInputData.user_enoccupation == 4">
                <p @click="CreateAccountFlag = true" class="regacc">注册账号</p>
                <p @click="ForgetPasswordFlag=true" class="regacc">忘记密码</p>
            </div>
            <!-- 记住密码/忘记密码 -->
            <div class="passwd">
                <el-checkbox v-model="userInputData.rpFlag" label="记住密码" size="large" />
            </div>
        </div>
    </div>
    <ForgetPassword v-model="ForgetPasswordFlag"></ForgetPassword>
    <CreateAccount v-model="CreateAccountFlag"></CreateAccount>
</template>

<script setup lang='js'>
// 引入模块
import { reactive, ref } from "vue";
import { User, Lock, CircleCheck } from "@element-plus/icons-vue";
import { userDataStore } from "../store/useUserDataStore.js"
import darkimg from "@/components/assets/Logo/Logo_dark.png"
import lightimg from "@/components/assets/Logo/Logo_light.png"
import router from '@/router';
import showMessage from "@/utils/showMessage.js";
// API
import getCaptchaAPI from "@/API/login/captcha.js";
import getSseintokenAPI from "@/API/login/sseintoken.js";
import getRolesAPI from "@/API/login/role.js";
import loginAPI from "@/API/login/login.js";
// modules
import CreateAccount from "./Utils/CreateAccount/CreateAccount.vue"
import ForgetPassword from "./Utils/ForgetPassword/ForgetPassword.vue";
const CreateAccountFlag = ref(false)
const ForgetPasswordFlag = ref(false)
// 全局用户pinia
const userData = userDataStore()
// 测试用,默认账号
const defaultData = {
    1: "0x2fa0af87d2dae54d6bb22dde9a123c7014a15676", //供应商
    2: "0x3c48fdd37aa547b5b0226ef4d03a24f67d248bfa", //中间商
    3: "0xe5815eae9ff49933031e1f0c533a203b7e4d6bdc" //超市
}
// 初始化提示数据
const message = {
    username: "请输入区块链地址",
    password: "请输入密码",
    user_enoccupation: "请选择您的角色",
    code: "请输入验证码"
}
// 路由映射
const routerRefer = {
    1: "/producer",
    2: "/broker",
    3: "/supermarket",
    4: "/consumer",
}
// 用户数据
const userInputData = reactive({
    username: localStorage.getItem("SLusername"),
    password: localStorage.getItem("SLpassword"),
    user_enoccupation: "",
    // user_enoccupation: 4,
    code: "",
    rpFlag: ""
})

// 验证码
const captchaImg = ref("")
const token = ref("")
async function getCaptcha() {
    const res = await getCaptchaAPI()
    captchaImg.value = 'data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
    const res2 = await getSseintokenAPI()
    token.value = res2.data
}
getCaptcha()

// 角色选择数据
const user_occupation = ref()
async function getRoles() {
    const res = await getRolesAPI()
    user_occupation.value = res.data.data
}
getRoles()
// 切换角色
function chaneCharacter(id) {
    switch (id) {
        case 1: { userInputData.username = defaultData[1]; return 0 }
        case 2: { userInputData.username = defaultData[2]; return 0 }
        case 3: { userInputData.username = defaultData[3]; return 0 }
        case 4: { userInputData.username = localStorage.getItem("SLusername"); return 0 }
    }

}

// 检测输入内容
function checkCont() {
    for (const i in userInputData) {
        if (!userInputData[i] && i != "rpFlag") {
            showMessage(message[i])
            return false
        }
    }
    return true
}
// 登录事件
async function login() {
    if (checkCont()) {
        rememberPassword()
        const res = await loginAPI(userInputData.username, userInputData.password, userInputData.user_enoccupation, userInputData.code, token.value)
        if (res.data.code == 200) {
            let varData = {
                "username": res.data.data,
                "token": res.data.toKen
            }
            localStorage.setItem("SLuserData", JSON.stringify(varData))
            showMessage("登录成功", "success")
            userData.loginMode = userInputData.user_enoccupation
            router.push("/home" + routerRefer[userInputData.user_enoccupation])
        }
        else {
            showMessage(res.data.msg)
        }
    }
}
// 记住密码
function rememberPassword() {
    if (userInputData.rpFlag) {
        if (userInputData.user_enoccupation == 4) { localStorage.setItem("SLusername", userInputData.username) }
        localStorage.setItem("SLpassword", userInputData.password)
    } else {
        localStorage.setItem("SLusername", "")
        localStorage.setItem("SLpassword", "")
    }
}
</script>

<style scoped>
/* 背景 */
.background {
    position: fixed;
    width: 100%;
    height: 100%;
    /* background: #000; */
    animation-name: ani;
    animation-duration: 10s;
    animation-direction: alternate-reverse;
    animation-iteration-count: infinite;
}

@keyframes ani {
    from {
        background-color: var(--Login_backGround1);
    }

    to {
        background-color: var(--Login_backGround2);
    }
}

/* 框架 */
.border {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* logo */
.logo {
    height: 150px;
    border-radius: 10px;
    margin-bottom: -30px;
}

/* 标题 */
.name {
    text-align: center;
    font-weight: bold;
    font-size: 30px;
    margin: 20px;
    color: var(--Login_textColor) !important;
    transition: all 0.5s;
}

/* 通用尺寸 */
.uinput,
.codebg,
.loginbtn,
.passwd,
.regacc {
    margin: 10px;
    width: 350px;
    height: 40px;
}

/* 验证码背景 */
.codebg {
    display: flex;
    justify-content: space-between;
    gap: 10px;
}

.codebg>img {
    height: 40px;
}

/* 记住/忘记密码 */
.passwd {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
}

.passwd>p,
.regacc {
    color: #0079fe;
    cursor: pointer;
}

.passwd>p:hover {
    cursor: pointer;
}

/* 注册 */
.regacc {
    font-size: 14px;
}

.plusFun {
    display: flex;
    width: 350px;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
}

.plusFun>* {
    margin: 0;
    width: auto;
    height: auto;
}
</style>